package com.example.dayu521.sg_oss.controller;

import com.alibaba.cloud.stream.binder.rocketmq.constant.RocketMQConst;
import com.example.dayu521.sg_oss.conf.AmqpCnf;
import com.example.dayu521.sg_oss.domain.msg.SimpleMsg;
import com.example.dayu521.sg_oss.service.OrderNumService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.dayu521.ORExecption;
import org.example.dayu521.OrRes;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/base")
public class BaseOrder {

    @Autowired
    private OrderNumService orderNumService;

    @Resource(name = "redisTemplate")
    private RedisTemplate<String,Long> s;

    @PostMapping("/getnumber")
    public OrRes<Long> getnumber() throws ORExecption {

        OrderNumService.NumState num_state = orderNumService.get_num_state();

        if(!num_state.is_expire()){

            long next_num = num_state.get_next_num();

            if(num_state.valid(next_num)){
                return OrRes.ok(num_state.getRes());
            }

            OrRes.error("订单号不满足当前约束,稍后再试").throw_x();
        }
        OrRes.error("服务超时,稍后再试").throw_x();
        return null;
    }

    @PostMapping("/getnumber2")
    public OrRes<?> getnumber2(){
        return OrRes.ok(s.opsForValue().increment("sg.order.incrby"));
    }

    @Autowired
    private StreamBridge streamBridge;

    @PostMapping("/send/{i}")
    public  OrRes<?> send(@RequestBody String pmsg, @PathVariable(required = false) int i){
        MessageBuilder builder = MessageBuilder.withPayload(new SimpleMsg(pmsg));
        builder.setHeader("test", String.valueOf(i))
                .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON);
        //监听器的arg参数将收到这个参数
        builder.setHeader(RocketMQConst.USER_TRANSACTIONAL_ARGS, "binder-ooo");
        Message<SimpleMsg> msg = builder.build();
        streamBridge.send("producer-out-0", msg);
        System.out.println("send Msg:" + msg.toString());
        return OrRes.ok();
    }
}
